/**
 * Copyright (C) 2011 Audit Logger Project. All rights reserved.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.auditlogger.security;

import java.security.InvalidParameterException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class EncryptionHelper {
	
	public static SecretKey generateSecretKey(String alg, int keySize) throws EncryptionException {
		if (alg == null || alg.trim().equals("")) {
			throw new IllegalArgumentException("Algorithm is null or empty");
		}
		if (keySize <=0) {
			throw new IllegalArgumentException (
					"Key size must be a positive value greater than 0");
		}
		// Don't use CipherSpec here to get algorithm as this may cause assertion
		// to fail (when enabled) if only algorithm name is passed to us.
		String[] cipherSpec = alg.split("/");
		String cipherAlg = cipherSpec[0];
		try {
		    // Special case for things like PBEWithMD5AndDES or PBEWithSHA1AndDESede.
		    // In such cases, the key generator should only request an instance of "PBE".
		    if ( cipherAlg.toUpperCase().startsWith("PBEWITH") ) {
		        cipherAlg = "PBE";
		    }
			KeyGenerator kgen =
				KeyGenerator.getInstance(cipherAlg);
			kgen.init(keySize);
			return kgen.generateKey();
		} catch (NoSuchAlgorithmException e) {
			throw new EncryptionException("Failed to generate random secret key." +
					"Invalid algorithm. Failed to generate secret key for " + alg + " with size of " 
					+ keySize + " bits.", e);
		} catch (InvalidParameterException e) {
			throw new EncryptionException("Failed to generate random secret key - invalid key size specified." +
					"Invalid key size. Failed to generate secret key for " + alg 
					+ " with size of " + keySize + " bits.", e);
		}
	}
}
